package controller;

import domain.Role;
import domain.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import service.IUserService;

import javax.annotation.security.RolesAllowed;
import java.util.List;

/**
 * @author Freedy
 * @date 2020/12/25 20:58
 */
@Controller
@RequestMapping("/user")
@RolesAllowed({"ADMIN"})
public class UserController {

    @Autowired
    private IUserService userService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll() throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        List<Users> userList=userService.findAll();
        modelAndView.addObject("userList",userList);
        modelAndView.setViewName("user-list");
        return modelAndView;
    }

    @RequestMapping("/save.do")
    public String save(Users users) throws Exception{
        userService.save(users);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findById.do")
    public ModelAndView findById(String id) throws Exception{
        ModelAndView modelAndView = new ModelAndView();
        Users user=userService.findById(id);
        modelAndView.addObject("user",user);
        modelAndView.setViewName("user-show-one");
        return modelAndView;
    }

    @RequestMapping("/findUserByIdAndAllRole.do")
    public ModelAndView findUserByIdAndAllRole(String id) throws Exception {
        ModelAndView modelAndView = new ModelAndView();
        Users user = userService.findById(id);
        List<Role> list=userService.findUserByIdAndAllRole(id);
        modelAndView.addObject("user",user);
        modelAndView.addObject("roleList",list);
        modelAndView.setViewName("user-role-add");
        return modelAndView;
    }

    @RequestMapping("/addRoleToUser.do")
    public String addRoleToUser(@RequestParam(name = "userId")String userId,
    @RequestParam(name = "ids")String[] roleIds) throws Exception {
        userService.addRoleToUser(userId,roleIds);
        return "redirect:findAll.do";
    }



}
